package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * returns expr1 – expr2 expressed setAliasAndSetNeedBuild a value in days from one date to the
 * other. expr1 and expr2 are date or date-and-time expressions. Only the date
 * parts of the columnValueList are used in the calculation.
 *
 * <pre>
 * mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
 *         -> 1
 * mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
 *         -> -31
 * </pre>
 */
public class DateDiff extends ScalarFunction {

    private static final Long DAY = 24 * 60 * 60 * 1000L;

    @SuppressWarnings("deprecation")

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp1 = Type.TimestampType.convert(args[0]);
        timestamp1.setHours(0);
        timestamp1.setMinutes(0);
        timestamp1.setSeconds(0);
        java.sql.Timestamp timestamp2 = Type.TimestampType.convert(args[1]);
        timestamp2.setHours(0);
        timestamp2.setMinutes(0);
        timestamp2.setSeconds(0);
        return (timestamp1.getTime() - timestamp2.getTime()) / DAY;
    }

    public Type getReturnType() {
        return Type.LongType;
    }

    public String[] getFunctionNames() {
        return new String[]{"DATEDIFF"};
    }
}
